import asyncio
from typing import List, Optional, Tuple
import os

from google.adk.agents.llm_agent import LlmAgent
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioServerParameters
from google.adk.tools import BaseTool
from google.adk.models.lite_llm import LiteLlm


# 全局变量用于存储工具集和退出栈
_tools: Optional[List[BaseTool]] = None
_exit_stack = None
_tools_lock = asyncio.Lock()

# --- Step 1: Import Tools from MCP Server ---
async def get_tools_async():
    """Gets tools from the ADK Web Tool MCP Server."""
    global _tools, _exit_stack
    
    async with _tools_lock:
        # 如果工具集已经加载，则直接返回
        if _tools is not None:
            return _tools, _exit_stack
            
        print("Attempting to connect to MCP ADK Web Tool server...")
        try:
            tools, exit_stack = await MCPToolset.from_server(
                connection_params=StdioServerParameters(
                    command='python', # Command to run the server
                    args=[
                        os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "crawl4ai", "mcp_crawler_server.py")
                    ],
                )
            )
            print("MCP Toolset created successfully.")
            # 保存到全局变量以便重用
            _tools = tools
            _exit_stack = exit_stack
            return tools, exit_stack
        except Exception as e:
            print(f"Error connecting to MCP server: {e}")
            # 当出错时，确保全局变量保持未初始化状态
            _tools = None
            _exit_stack = None
            raise

# --- 创建一个供ADK系统使用的静态agent ---
# 这是ADK系统导入时将直接使用的对象
root_agent = LlmAgent(
    model=LiteLlm(model="deepseek/deepseek-chat"),
    name='crawl4ai_agent',
    description=(
        "网页内容总结专家"
    ),
    instruction=(
        """
        你是一个网页内容总结专家，能够使用网页爬虫工具获取网页内容并进行智能分析和总结。
        请尽可能提供详细且有结构的信息，按照网页的主要内容组织你的回答。
        """),
    tools=[],  # 初始时没有工具，将在运行时添加
)

# --- 运行时agent初始化函数 ---
async def initialize_agent():
    """在运行时初始化agent，添加MCP工具"""
    global root_agent
    
    # 获取MCP工具
    tools, _ = await get_tools_async()
    
    # 动态更新agent的tools属性
    root_agent.tools = tools
    
    print(f"Agent initialized with {len(tools)} tools.")
    return root_agent 